﻿using System.Text;
using System.Diagnostics;
using System.IO;

namespace ServBus.ListForm2010.Utility
{
    public class CabCreater
    {
        private InfoPathContext mContext;

        public CabCreater(InfoPathContext context)
        {
            mContext = context;
        }

        public void Create()
        {
            CreateCabIndexFile();
            string a = System.Environment.SystemDirectory;

            Process proc = new Process();
            proc.StartInfo = new ProcessStartInfo(System.Environment.SystemDirectory + @"\makecab.exe", "/f " + mContext.Path + @"\test.ddf");
            proc.StartInfo.WorkingDirectory = mContext.Path;
            proc.Start();
            mContext.XsnPath = mContext.Path + "test\\" + mContext.TemporaryXsnName;
        }

        private string GetXsnName()
        {
            string name = string.Empty;
            foreach (string str in mContext.SelectedContent.Keys)
            {
                name += "_" + str + "_" + mContext.SelectedContent[str];
            }

            return name.Trim(new char[] { '_' });
        }

        private void CreateCabIndexFile()
        {
            string fileTemp = NameSpaceConstants.TemplateRootPath + "test.ddf";
            string baseContent = File.ReadAllText(fileTemp, Encoding.UTF8);
            baseContent = string.Format(baseContent, mContext.TemporaryXsnName);
            string fileNames = null;
            foreach (string fileName in mContext.FilesBeSaved)
            {
                fileNames += fileName + "\r\n";
                //将文件的编码都改为utf-8
                Utility.ConvertFileEncoding(mContext.Path + "\\" + fileName, null, Encoding.UTF8);
            }

            Utility.WriteContentToFile(mContext.Path + "test.ddf", baseContent + fileNames);

        }
    }
}
